package com.cnswhy.cloud.server.app.filter;

import com.cnswhy.cloud.common.redis.service.RedisService;
import com.cnswhy.cloud.server.app.exception.LoginExecption;
import com.cnswhy.cloud.server.core.constant.RedisConstant;
import com.cnswhy.cloud.server.core.entity.Customer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;

/**
 * 后台管理用户session拦截器
 * 
 * @author qiuxw
 *
 */
@Slf4j
@Component
public class LoginInterceptor extends HandlerInterceptorAdapter
{
	
	
	@Autowired
	private RedisService iJedisRedisProxy;
	
	@Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
    {
    	if (request.getMethod().equals( "OPTIONS" )) {
            response.setStatus(200);
            return true;
        }
    	String sessionId = (String)request.getHeader("sessionId");
        HttpSession session = request.getSession();
        log.info("=======================>login interceptor user session id："+sessionId);
		Customer customer = (Customer) iJedisRedisProxy.hget(RedisConstant.CUSTOMER_SESSION_KEY, sessionId);
        if (null == customer)
        {
            session.removeAttribute(sessionId);
	        // ajax请求类型
	        String requestType = request.getHeader("X-Requested-With");
	        if ("XMLHttpRequest".equals(requestType))
	        {
	        	response.sendError(4,"User has not login");
	        	response.getOutputStream().print("no login");
	            //throw new LoginExecption(-2,"请重新登录");
	            //response.addHeader("sessionstatus", "timeOut");
	            //response.sendError(555, "User has not login");
	            //response.setCharacterEncoding("UTF-8");
	            //response.getOutputStream().print(JSON.toJSONString(res));
	            //return false;
	        	return false;
	        }else{
	            //页面请求
	        	response.setStatus(4);
	        	response.getWriter().print("no login");
	            return false;
	        }
        }
        else
        {
        	
           String sid = (String)iJedisRedisProxy.hget(RedisConstant.CUSTOMER_SESSION_ID, String.valueOf(customer.getId()));
           //log.info("=======================>login sid: "+sid);
           //log.info("=======================>current sid: "+sessionId);
           //log.info("exist: {}",sid.equals(sessionId));
           if(!sid.equals(sessionId))
           {
           		log.info("Log in somewhere else ！！");
               throw new LoginExecption(-2,"当前账号在别的设备登录");
           }
                
        }
        //24小时过期
        iJedisRedisProxy.hset(RedisConstant.CUSTOMER_SESSION_KEY, sessionId, customer, 60*60*24L);

        //增加token校验。Created by JSW on 2018/06/05
/*        String requestType = request.getHeader("X-Requested-With");
        if ("XMLHttpRequest".equals(requestType))
        {
            if (request.getSession() != null) 
            {
                Map<String, String[]> parameterMap = request.getParameterMap();
                CurrentUser user = (CurrentUser)request.getSession().getAttribute(Constants.USER_LOGIN_FLAG);
                if (user != null) 
                {
                    HashMap<String,String> paramsMap = getBody(request);
                    String md5Key = MD5.md5s(Constants.TOKEN_KEY_PRE+user.getSysUser().getId());
                    String tokenVal = paramsMap.get(md5Key);
                    if(StringUtils.isEmpty(tokenVal))
                    {
                        if (parameterMap != null && !parameterMap.isEmpty() && parameterMap.get(md5Key) != null
                                && parameterMap.get(md5Key).length > 0) 
                        {
                            tokenVal = parameterMap.get(md5Key)[0];
                        }
                    }
                    Object redisTokenObj = iJedisRedisProxy.get(md5Key);
                    String redisToken = redisTokenObj!=null?String.valueOf(redisTokenObj):null;
                    if(tokenVal==null || redisToken == null || !tokenVal.equals(redisToken))
                    {
                        response.addHeader("sessionstatus", "timeOut");
                        response.addHeader("loginPath", "/login/loginIndex?dir=1");
                        response.sendError(555, "User has not login");
                        return false;
                    }
                }
            }
        }*/

        // 转移到下一个拦截器
        return super.preHandle(request, response, handler);
    }
	
	public static HashMap<String, String> getBody(HttpServletRequest request) throws IOException
	{
		
		HashMap<String, String> bodyMap = new HashMap<String, String>();
		
		StringBuilder stringBuilder = new StringBuilder();
		BufferedReader bufferedReader = null;
		
		try
		{
			InputStream inputStream = request.getInputStream();
			if (inputStream != null)
			{
				bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
				char[] charBuffer = new char[128];
				int bytesRead = -1;
				while ((bytesRead = bufferedReader.read(charBuffer)) > 0)
				{
					stringBuilder.append(charBuffer, 0, bytesRead);
					String[] paramsArr = stringBuilder.toString().split("=");
					bodyMap.put(paramsArr[0], paramsArr[1]);
				}
			}
			else
			{
				stringBuilder.append("");
			}
		}
		catch (IOException ex)
		{
			throw ex;
		}
		finally
		{
			if (bufferedReader != null)
			{
				try
				{
					bufferedReader.close();
				}
				catch (IOException ex)
				{
					throw ex;
				}
			}
		}
		
		return bodyMap;
	}
	
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception
	{
		super.postHandle(request, response, handler, modelAndView);
	}
	
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception
	{
		// TODO Auto-generated method stub
		super.afterCompletion(request, response, handler, ex);
	}
}
